import { pathResolve } from "@/utils/routerHelper";
import { ElSubMenu, ElMenuItem } from "element-plus";
import { useRenderMenuTitle } from "./useRenderMenuTitle";
import { isUrl } from "@/utils/is";
import { hasOneChildren } from "../helper"
import { MyIcon } from "@/components/MyIcon";

export const useRenderMenuItem = () => {
  const { renderMenuTitle } = useRenderMenuTitle();
  const renderMenuItem = (routers: any, parentPath = "/") => {
    return routers
      .filter((route: any) => !route.meta?.hidden)
      .map((item: any) => {
        const fullPath = isUrl(item.path) ? item.path : pathResolve(parentPath, item.path);
        const meta = item.meta ?? {};
        const { onlyOneChildren, oneChildren } = hasOneChildren(item.children, item)

        // 判断是否是一个子菜单
        const menuItemIcon = oneChildren?.meta?.icon

        // 判断是否只有一个子菜单并且该子菜单没有子菜单或者该子菜单不是一个子菜单
        if (onlyOneChildren && (!oneChildren?.children || oneChildren.noOneChildren) && !item.meta.alwaysShow) {
          return (
            <ElMenuItem key={item.path} index={pathResolve(fullPath, oneChildren.path)}>
              {{
                title: () => renderMenuTitle(oneChildren ? { ...oneChildren.meta, icon: null } : { ...meta, icon: null }),
                default: () => menuItemIcon ? <MyIcon icon={menuItemIcon}></MyIcon> : '',
              }}
            </ElMenuItem>
          );
        } else {
          return (
            <ElSubMenu key={item.path} index={fullPath}>
              {{
                title: () => renderMenuTitle(item.meta),
                default: () => renderMenuItem(item.children, fullPath),
              }}
            </ElSubMenu>
          );
        }
      });
  };

  return {
    renderMenuItem,
  };
};
